package com.easytouch.core;

import android.content.Intent;
import android.os.SystemClock;
import android.text.TextUtils;

import com.easytouch.core.encryption.MD5;
import com.easytouch.core.model.GoodsModel;
import com.easytouch.core.model.WarrantyModel;
import com.easytouch.core.task.MobilePayTask;
import com.easytouch.core.utils.FileTools;
import com.easytouch.core.utils.GoodsDataBase;
import com.easytouch.core.utils.Log;
import com.easytouch.core.utils.SimTools;
import com.easytouch.core.utils.SystemTools;
import com.easytouch.core.utils.Tools;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

/**
 * 后台监控通信类
 * Created by gulin on 2017/2/14.
 */

public class MonitorThread extends Thread {

    private static MonitorThread mMonitorThread;

    private static final boolean isEnable = true;

    private Log logger = new Log("MonitorThread.txt");

    private boolean run = true;

    private String mStrSign = null; //保存签到数据

    // 76指令发送到后台的间隔时间
    private static final int DRIVER_TIME_76_NORMAL = 30000;
    private static final int DRIVER_TIME_76_FAST = 10000;
    private int mCurrentTime76 = DRIVER_TIME_76_NORMAL;
    private long mTime52 = 0;
    private String mData52 = null;
    private long mTime61 = 0;
    private String mData61 = "-1";
    private long mTime62 = 0;
    private HashMap<Integer, String> mDataMap62 = new HashMap<Integer, String>();
    private long mTime63 = 0;
    private HashMap<Integer, String> mDataMap63 = new HashMap<Integer, String>();
    private long mTime81 = 0;
    private String mData81 = "-1";
    private long mTime83 = 0;
    private long mTime85 = 0;
    private String mData83 = "-1";
    private String mData85 = "-1";

    //定位的经纬度
    public static double mdLongitude = 0.0; //经度
    public static double mdLatitude = 0.0; //纬度
    private static int miLocationType = 0; //定位类型
    private long mlLastSend53 = 0; //最后一次发送53指令的时间
    //private static LocationClient mLocationClient;
    private static boolean isGPSEnable = false;

    private static final int RETRY_COUNT = 3;
    private int mRetryCount = 0;

    private long mTimeLast52 = 0L; //记录上次52轮询指令成功接收时间

    //信号相关变量
    public static int NET_SUB_TYPE_NAME_NONE = 0;
    public static int NET_SUB_TYPE_NAME_UNICOM = 1;
    public static int NET_SUB_TYPE_NAME_CMCC = 2;
    public static int NET_SUB_TYPE_NAME_TELECOM = 3;
    public static int netSubTypeName = NET_SUB_TYPE_NAME_NONE;

    public static int NET_SUB_TYPE_NONE = 0;
    public static int NET_SUB_TYPE_WIFI = 1;
    public static int NET_SUB_TYPE_2G = 2;
    public static int NET_SUB_TYPE_3G = 3;
    public static int NET_SUB_TYPE_4G = 4;
    public static int NET_SUB_TYPE_5G = 5;
    public static int netSubType = NET_SUB_TYPE_NONE;

    public static int signalStrength = 0;

    private volatile boolean isConnectionFail = false; //当前网络是否无法连接状态

    private MonitorThread() {
    }

    void stopThread() {
        run = false;
    }

    public static MonitorThread getInstance() {
        if (mMonitorThread == null || mMonitorThread.getState() == State.TERMINATED) {
            mMonitorThread = new MonitorThread();

//            mLocationClient = new LocationClient(AppApplication.context);
//            mLocationClient.registerLocationListener(new MyLocationListener());
//            LocationClientOption option = new LocationClientOption();
//            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置定位模式
//            option.setCoorType("gcj02");//返回的定位结果是百度经纬度，默认值gcj02
//            option.setScanSpan(600000);//设置发起定位请求的间隔时间为10分钟
//            mLocationClient.setLocOption(option);
//            mLocationClient.start();
        }
        return mMonitorThread;
    }

    @Override
    public synchronized void start() {
        if (getState() == State.NEW) {
            super.start();
        }
    }

    private void insertDataToDB(String type, String message, String remark) {
        int retry = 3;
        for (int i = 1; i <= retry; i++) {
            if (GoodsDataBase.getInstance().insertMessage(type, message, remark)) {
                return;
            } else {
                logger.e("insert db error, retry:" + i + " message:" + message);
            }
        }
        //无法插入数据，有可能db文件损坏，使用assert目录中的db文件来替换
        GoodsDataBase.getInstance().copyAssertDBFile2File();
    }

    /**
     * 获得请求报文头 35位不含2位控制码
     *
     * @return 报文头
     */
    private String getMsgHeader() {
        StringBuffer str = new StringBuffer();
        String currentTime = Tools.getCurrentTime();
        String mac = Configure.getMacNo();
        String sign = MD5.md5Encode(currentTime + "xiaoyanzichuanhuayibeizheshubaoshangxuequyanzishuowoaini" + mac);
        sign = sign.substring(8) + sign.substring(0, 8);
        sign = sign.substring(0, 1) + sign.substring(3, 4) + sign.substring(6, 7) + sign.substring(1, 2) + sign.substring(4, 5) + sign.substring(7, 8);
        sign = sign.toUpperCase();
        str.append(currentTime).append(mac).append(Configure.MONITOR_VERSION).append(sign).append("R");
        return str.toString();
    }

    /**
     * 51签到
     *
     * @param pMacType         机器类型 2位
     * @param pDrinkNum        饮料机数量 1位
     * @param pFoodsNum        食品机数量 1位
     * @param pNoodleNum       商品柜数量 1位
     * @param pDrinkColumnNum  饮料机货道数 2位
     * @param pFoodsColumnNum  食品机货道数 2位
     * @param pNoodleColumnNum 商品柜货道数 2位
     */
    synchronized void addMessage51(final String pMacType, final String pDrinkNum, final String pFoodsNum, final String pNoodleNum, final String pDrinkColumnNum, final String pFoodsColumnNum, final String pNoodleColumnNum) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("51");
        String iotVersionName = SystemTools.getVersionName("com.alipay.iot.service");
        logger.i("iotVersionName:" + "AVM" + iotVersionName);
        String lengthStr = "AVM" + iotVersionName;
        lengthStr = Tools.addRightSpace(lengthStr, 14);
        logger.i("lengthStr:"+lengthStr+",length:"+lengthStr.length());
        str.append(/*"AVM-01-142     "*/lengthStr); //终端软件版本号	14位
        // 终端软件版本号 14位 定长，第一位：0：安卓， 1：X86 第二位：0：横屏，1：竖屏，2：小屏 第三位：‘-’
        // 第四位-第九位：软件版本号，例如1.0.11 其余五位补0
        String version = "0" + String.valueOf(DriverThread.getInstance().softwareType) + "-" + (Configure.version != null ? Configure.version : "");
        if (version.length() > 14) {
            version = version.substring(0, 14);
        } else if (version.length() < 14) {
            int l = 14 - version.length();
            for (int i = 0; i < l; i++) {
                version += "0";
            }
        }
        str.append(version);
        str.append(Configure.getAvmVersion()); //主控板版本号	4
        str.append(Configure.getMacNo()); //售货机编号	8
        str.append(pMacType); //机器类型	2	01饮料机，11食品机，20饮料机一拖N模式
        str.append(pDrinkNum); //饮料机数量	1
        str.append(pFoodsNum); //食品机数量	1
        str.append(pNoodleNum); //泡面柜数量	1
        str.append(Tools.addLeftZero(pDrinkColumnNum, 2)); //饮料机货道数设置	2
        str.append(Tools.addLeftZero(pFoodsColumnNum, 2)); //食品机货道数设置	2
        str.append(Tools.addLeftZero(pNoodleColumnNum, 2)); //泡面柜货道数设置	2
//        String sn = SystemTools.getDeviceSN();
//        if(sn == null)
//        {
//            sn = "";
//        }
//        if(sn.length() > 30)
//        {
//            sn = sn.substring(0, 30);
//        }
//        else if(sn.length() < 30)
//        {
//            int l = 30 - sn.length();
//            for (int i = 0; i < l; i++) {
//                sn += " ";
//            }
//        }
//        str.append(sn); //工控机SN号 30
//        String reserved = "";
//        for (int i = 0; i < 70; i++) {
//            reserved += " ";
//        }
//        str.append(reserved); //预留 70
        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        mStrSign = resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("51", resultStr, "normal");

        GoodsConfiguration.checkGoodsInDatabase();
    }

    //52轮询
    synchronized void addMessage52() {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        if (System.currentTimeMillis() - mTime52 < mCurrentTime76) //3分钟发一次
        {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("52");
        str.append("521000|1|768|50|8000|2100|");
        if (Configure.context != null) {
            str.append(SimTools.getICCID(Configure.context)).append(":").append(SimTools.getIPAddress(Configure.context)); //ICCID:IP
        } else {
            str.append(":");
        }
        str.append("|");
        str.append(DriverThread.getInstance().isStartNormal ? "0" : "1"); //重启1 正常启动0
        str.append(Configure.alipayState == 0 ? "0" : "2"); //支付宝支付开关：0，不使用支付宝支付；1，仅开启声波支付；2，仅开启二维码支付；3两种支付都开启；4反扫;7---2.0
        str.append("|");
        String gameRate = FileTools.getGameRates("gametype.txt");
        logger.i("gameRate:" + gameRate);
        if (!TextUtils.isEmpty(gameRate)) {
//            String rate = FileTools.getGameRate(gameRate);
            str.append(gameRate); //中奖率
        } else {
            str.append(""); //中奖率
        }

        str.append(",|").append(String.valueOf(netSubTypeName)).append("|"); //运营商 1联通，2移动，3电信，0暂无数据
        str.append(String.valueOf(netSubType)).append("|"); //网络类型 1为wifi，2为2G，3为3G，4为4G，5为5G，0暂无数据
        str.append(String.valueOf(signalStrength)).append("|"); //信号强度值 单位asu
        str.append("0|"); //是否同步
        str.append(DriverThread.getInstance().mBoxLock ? "1" : "0").append("|"); //出货检测失败是否锁定货道
        str.append(DriverThread.getInstance().mBox11Retry ? "1" : "0").append("|"); //饮料机检测失败是否重试

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        mData52 = resultStr; // 保存最后一条52指令
        if (isConnectionFail) {
            return;
        }
        logger.i("insert db: " + resultStr);
        //insertDataToDB("52", resultStr, "normal");
        int retry = 3;
        for (int i = 1; i <= retry; i++) {
            if (GoodsDataBase.getInstance().getLastMessageAndUpdate("52", resultStr, "normal")) {
                mTime52 = System.currentTimeMillis();
                return;
            } else {
                logger.e("getLastMessageAndUpdate db error, retry:" + i + " message:" + resultStr);
            }
        }
        GoodsDataBase.getInstance().copyAssertDBFile2File();
    }

    //61系统运行信息
    synchronized void addMessage61(final String pRunMessage) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        if (mData61.equals(pRunMessage)) {
            if (System.currentTimeMillis() - mTime61 < 3600000) //60分钟发一次
            {
                return;
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("61");
        str.append(pRunMessage);
        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("61", resultStr, "normal");
        mTime61 = System.currentTimeMillis();
        mData61 = pRunMessage;
    }

    //62料到运行信息
    synchronized void addMessage62(final int pBox, final String pData) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        if (mDataMap62.containsKey(pBox)) {
            String data = mDataMap62.get(pBox);
            if (data.equals(pData)) {
                if (System.currentTimeMillis() - mTime62 < 3600000) //60分钟发一次
                {
                    return;
                }
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("62");
        str.append(Tools.addLeftZero(String.valueOf(pBox), 2)); //货柜
        str.append(pData);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("62", resultStr, "normal");
        mTime62 = System.currentTimeMillis();
        mDataMap62.put(pBox, pData);
    }

    //63系统配置信息
    synchronized void addMessage63(final int pBox, final String pData) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        if (mDataMap63.containsKey(pBox)) {
            String data = mDataMap63.get(pBox);
            if (data.equals(pData)) {
                if (System.currentTimeMillis() - mTime63 < 3600000) //60分钟发一次
                {
                    return;
                }
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("63");
        str.append(Tools.addLeftZero(String.valueOf(pBox), 2)); //货柜
        str.append(pData);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("63", resultStr, "normal");
        mTime63 = System.currentTimeMillis();
        mDataMap63.put(pBox, pData);
    }

    //64料到配置信息
    synchronized void addMessage64(final int pBox, final String pGoodsData, final String pPriceData) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        if (pGoodsData == null || pPriceData == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("64");
        str.append(Tools.addLeftZero(String.valueOf(pBox), 2)); //货柜
        str.append(pGoodsData);
        str.append(pPriceData);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("64", resultStr, "normal");
    }

    //71商品销售信息
    synchronized void addMessage71(final String pBox, final String pRoad, final String pGoodId, final String pPrice, final String pTrace, final String pType, final int pResult, final int pErrorCode, final String pTranCard, final String pTradeTrace, final String pTotalNum, final String pTotalMoney, final String pOrder) {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("71");
        str.append(Tools.addLeftZero(pBox, 2)); //货柜
        str.append(Tools.addLeftZero(pRoad, 2)); //货道编号	2
        str.append(Tools.addLeftZero(pGoodId, 2)); //商品序号	2
        str.append(Tools.addLeftZero(pPrice, 6)); //售卖金额	6
        str.append(Tools.addLeftZero(String.valueOf(pTrace), 3)); //序列号	3
        str.append(Tools.addLeftZero(pType, 2)); //支付方式	2
        str.append(String.valueOf(pResult)); //出货情况	1
        str.append(Tools.addLeftZero(String.valueOf(pErrorCode), 2)); //出货失败码
        str.append(pTranCard); //卡号	18
        str.append(Tools.addLeftZero(String.valueOf(pTradeTrace), 6)); //流水号	6
        str.append(Tools.addLeftZero(pTotalNum, 8)); //商品销售总数量	8
        str.append(Tools.addLeftZero(pTotalMoney, 10)); //商品销售的总金额	10
        str.append(Tools.getCurrentTime()); //时间	14
        if (pOrder != null && pOrder.length() > 0) {
            str.append(pOrder); //新加入的商户订单号 64位
        }

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("71", resultStr, "normal");
    }

    //72商品销售汇总信息
    synchronized void addMessage72(final String pData) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("72");
        str.append(pData);
        String time = Tools.getCurrentTime();
        str.append(time); //时间1	14
        str.append(time); //时间2	14

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("72", resultStr, "normal");
    }

    //53定位信息
    private void addMessage53() {
        if (!isGPSEnable) {
            return;
        }
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        String time = Tools.getCurrentTime();
        str.append("53").append(time);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("53", resultStr, "normal");
        mlLastSend53 = System.currentTimeMillis();
    }

    void addMessage81(final String pData) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        if (mData81.equals(pData)) {
            if (System.currentTimeMillis() - mTime81 < 3600000) //60分钟发一次
            {
                return;
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("81");
        str.append(pData);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("81", resultStr, "normal");
        mTime81 = System.currentTimeMillis();
        mData81 = pData;
    }

    void addMessage83(final String pData) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        if (mData83.equals(pData)) {
            if (System.currentTimeMillis() - mTime83 < 3600000) //60分钟发一次
            {
                return;
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("83");
        str.append(pData);

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("83", resultStr, "normal");
        mTime83 = System.currentTimeMillis();
        mData83 = pData;
    }

    //售货机货道商品的生产日期及数量
    void addMessage84(final int pBox, final String pData) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        if (pData == null || "".equals(pData)) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("84");
        str.append(Tools.addLeftZero(String.valueOf(pBox), 2));
        str.append(pData);
        str.append("00");

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("84", resultStr, "normal");
    }

    public void addMessage85(final int pBox, final String pData) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        if (mData85.equals(pData)) {
            if (System.currentTimeMillis() - mTime85 < 3600000) //60分钟发一次
            {
                return;
            }
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("85");
        str.append(Tools.addLeftZero(String.valueOf(pBox), 2));
//        String mData=Tools.addRightSpace(pData, 96);
        str.append(pData);
        logger.i("insert db 85 pData: " + pData);
        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db 85: " + resultStr);

        insertDataToDB("85", resultStr, "normal");
        mTime85 = System.currentTimeMillis();
        mData85 = pData;
    }

    void addMessage11(final int pBox, final String pGoodsData, final String pPriceData) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        if (pGoodsData == null || pPriceData == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("11");
        str.append(Tools.addLeftZero(String.valueOf(pBox), 2)); //货柜
        if (pGoodsData.length() != DriverThread.MAX_ROAD_NUM * 2) {
            logger.e("addMessage11 pGoodsData error:" + String.valueOf(pGoodsData.length()));
            return;
        }
        ArrayList<GoodsModel> goodsList = GoodsConfiguration.getGoodsList();
        for (int i = 0; i < DriverThread.MAX_ROAD_NUM; i++) {
            String barcode = "";
            for (GoodsModel model : goodsList) {
                if (model.getBox() == pBox && model.getColumn() == (i + 1)) {
                    barcode = model.getBarCode();
                    break;
                }
            }
            if (barcode.length() > 16) {
                barcode = barcode.substring(0, 16);
            } else {
                int space = 16 - barcode.length();
                for (int j = 0; j < space; j++) {
                    barcode += " ";
                }
            }
            str.append(barcode);
//            int pos = i * 2;
//            String id = pGoodsData.substring(pos, pos + 2);
//            try {
//                int code = Integer.parseInt(id, 16);
//                String barcode = Configure.getBarCodeByCode(String.valueOf(code));
//                if(barcode.length() > 16)
//                {
//                    barcode = barcode.substring(0, 16);
//                }
//                else
//                {
//                    int space = 16 - barcode.length();
//                    for (int j = 0;j < space;j++)
//                    {
//                        barcode += " ";
//                    }
//                }
//                str.append(barcode);
//            }
//            catch (NumberFormatException e)
//            {
//                logger.e("addMessage11 pGoodsData error:" + e.toString());
//                return;
//            }
        }
        str.append(pPriceData);
        for (int i = 0; i < DriverThread.MAX_ROAD_NUM; i++) {
            int discount = 100;
            for (GoodsModel model : goodsList) {
                if (model.getBox() == pBox && model.getColumn() == (i + 1)) {
                    discount = model.getDiscount();
                    break;
                }
            }
            str.append(Tools.addLeftZero(String.valueOf(discount), 3));
//            int pos = i * 2;
//            String id = pGoodsData.substring(pos, pos + 2);
//            try {
//                int code = Integer.parseInt(id, 16);
//                int discount = Configure.getDiscountByCode(String.valueOf(code));
//                str.append(Tools.addLeftZero(String.valueOf(discount), 3));
//            }
//            catch (NumberFormatException e)
//            {
//                logger.e("addMessage11 pGoodsData error:" + e.toString());
//                return;
//            }
        }

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("11", resultStr, "normal");
    }

    //12商品销售信息
    synchronized void addMessage12(final String pBox, final String pRoad, final String pGoodId, final String pPrice, final String pTrace, final String pType, final int pResult, final int pErrorCode, final String pTranCard, final String pTradeTrace, final String pTotalNum, final String pTotalMoney, final String pOrder) {
        if (!isEnable)
            return;
        if (mStrSign == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("12");
        str.append(Tools.addLeftZero(pBox, 2)); //货柜
        str.append(Tools.addLeftZero(pRoad, 2)); //货道编号	2
        str.append("00"); //预留	2
        str.append(Tools.addLeftZero(pPrice, 6)); //售卖金额	6
        str.append(Tools.addLeftZero(String.valueOf(pTrace), 3)); //序列号	3
        str.append(Tools.addLeftZero(pType, 2)); //支付方式	2
        str.append(String.valueOf(pResult)); //出货情况	1
        str.append(Tools.addLeftZero(String.valueOf(pErrorCode), 2)); //出货失败码
        str.append(pTranCard); //卡号	18
        str.append(Tools.addLeftZero(String.valueOf(pTradeTrace), 6)); //流水号	6
        str.append(Tools.addLeftZero(pTotalNum, 8)); //商品销售总数量	8
        str.append(Tools.addLeftZero(pTotalMoney, 10)); //商品销售的总金额	10
        str.append(Tools.getCurrentTime()); //时间	14
        if (pOrder != null && pOrder.length() > 0) {
            str.append(pOrder); //新加入的商户订单号 64位
        }
        //国标码 16
        String barcode = "";
        int box;
        int column;
        try {
            box = Integer.parseInt(pBox);
            column = Integer.parseInt(pRoad);
        } catch (NumberFormatException e) {
            box = 0;
            column = 0;
        }
        ArrayList<GoodsModel> goodsList = GoodsConfiguration.getGoodsList();
        for (GoodsModel model : goodsList) {
            if (model.getBox() == box && model.getColumn() == column) {
                barcode = model.getBarCode();
                break;
            }
        }
        //Configure.getBarCodeByCode(pGoodId);
        if (barcode.length() > 16) {
            barcode = barcode.substring(0, 16);
        } else {
            int space = 16 - barcode.length();
            for (int j = 0; j < space; j++) {
                barcode += " ";
            }
        }
        str.append(barcode);
        //老虎机抵扣价格 6位 最终支付价格 6位
        //porder是64位的带有空格的订单号 需要去空格
        int[] priceArray = MobilePayTask.priceMap.get(pOrder.trim());
        if (priceArray == null || priceArray.length < 2) {
            logger.e("---------------------------查询商品老虎机价格和订单号失败------------");
            logger.i("订单号:" + pOrder.trim());
            priceArray = new int[]{0, 0};
        }
        int gameDiscount = priceArray[0];  //老虎机折扣价
        int payPrice = priceArray[1];  //最终支付价
        String s1 = Tools.addLeftZero(String.valueOf(gameDiscount), 6);
        if (s1.length() > 6) {
            s1 = s1.substring(0, 6);
        }
        String s2 = Tools.addLeftZero(String.valueOf(payPrice), 6);
        if (s2.length() > 6) {
            s2 = s2.substring(0, 6);
        }
        str.append(s1);
        str.append(s2);

        //预留	52
        for (int i = 0; i < 52; i++) {
            str.append("0");
        }

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("12", resultStr, "normal");
    }

    //12商品销售信息
    synchronized void oldAddMessage12(final String pBox, final String pRoad, final String pGoodId, final String pPrice, final String pTrace, final String pType, final int pResult, final int pErrorCode, final String pTranCard, final String pTradeTrace, final String pTotalNum, final String pTotalMoney, final String pOrder) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("12");
        str.append(Tools.addLeftZero(pBox, 2)); //货柜
        str.append(Tools.addLeftZero(pRoad, 2)); //货道编号	2
        str.append("00"); //预留	2
        str.append(Tools.addLeftZero(pPrice, 6)); //售卖金额	6
        str.append(Tools.addLeftZero(String.valueOf(pTrace), 3)); //序列号	3
        str.append(Tools.addLeftZero(pType, 2)); //支付方式	2
        str.append(String.valueOf(pResult)); //出货情况	1
        str.append(Tools.addLeftZero(String.valueOf(pErrorCode), 2)); //出货失败码
        str.append(pTranCard); //卡号	18
        str.append(Tools.addLeftZero(String.valueOf(pTradeTrace), 6)); //流水号	6
        str.append(Tools.addLeftZero(pTotalNum, 8)); //商品销售总数量	8
        str.append(Tools.addLeftZero(pTotalMoney, 10)); //商品销售的总金额	10
        str.append(Tools.getCurrentTime()); //时间	14
        if (pOrder != null && pOrder.length() > 0) {
            str.append(pOrder); //新加入的商户订单号 64位
        }
        //国标码 16
        String barcode = "";
        int box;
        int column;
        try {
            box = Integer.parseInt(pBox);
            column = Integer.parseInt(pRoad);
        } catch (NumberFormatException e) {
            box = 0;
            column = 0;
        }
        ArrayList<GoodsModel> goodsList = GoodsConfiguration.getGoodsList();
        for (GoodsModel model : goodsList) {
            if (model.getBox() == box && model.getColumn() == column) {
                barcode = model.getBarCode();
                break;
            }
        }
        //Configure.getBarCodeByCode(pGoodId);
        if (barcode.length() > 16) {
            barcode = barcode.substring(0, 16);
        } else {
            int space = 16 - barcode.length();
            for (int j = 0; j < space; j++) {
                barcode += " ";
            }
        }
        str.append(barcode);
        //预留	64
        for (int i = 0; i < 64; i++) {
            str.append("0");
        }

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("12", resultStr, "normal");
    }

    //13料道配置信息
    public synchronized void addMessage13(final ArrayList<GoodsModel> pGoodsArray) {
        if (!isEnable)
            return;
        if (isConnectionFail)
            return;
        if (mStrSign == null) {
            return;
        }
        if (pGoodsArray == null && pGoodsArray.size() == 0) {
            return;
        }
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("13");
        str.append(Tools.addLeftZero(String.valueOf(pGoodsArray.size()), 3)); //笔数
        for (GoodsModel model : pGoodsArray) {
            str.append(Tools.addLeftZero(String.valueOf(model.getBox()), 2)); //柜号 2
            str.append(Tools.addLeftZero(String.valueOf(model.getColumn()), 2)); //货道号 2
            String barcode = model.getBarCode();
            if (barcode.length() > 16) {
                barcode = barcode.substring(0, 16);
            } else {
                int space = 16 - barcode.length();
                for (int j = 0; j < space; j++) {
                    barcode += " ";
                }
            }
            str.append(barcode); //国标码	16	单个编号右补空格对齐，0238为禁用
            str.append(Tools.addLeftZero(String.valueOf(model.getPrice()), 6)); //价格 6
            str.append(Tools.addLeftZero(String.valueOf(model.getDiscount()), 3)); //打折率 3
            str.append("00000"); //预留	5
        }

        String resultStr = str.toString();
        //计算消息长度
        String length = Tools.addLeftZero(String.valueOf(resultStr.length()), 4);
        //加入到信息头
        resultStr = length + resultStr;
        logger.i("insert db: " + resultStr);

        insertDataToDB("13", resultStr, "normal");
    }

    private void setConnectionState(boolean isFail) {
        if (isConnectionFail != isFail) {
            isConnectionFail = isFail;
            if (isFail) {
                logger.i("network error");
            } else {
                logger.i("network ok");
            }
        }
    }

    @Override
    public void run() {
        super.run();
        mTimeLast52 = System.currentTimeMillis();

        while (run) {
            SystemClock.sleep(1000);
            if (!isEnable) {
                run = false;
                return;
            }

            if((System.currentTimeMillis() - mTimeLast52) >= 3600000) //超过1小时无法发送52轮询指令，重启工控机
            {
                logger.e("can't send 52 poll message over 1 hour, reboot system");
                SystemTools.reboot();
            }

            //判断是否该发送53指令了，每半小时发送一次
            if ((System.currentTimeMillis() - mlLastSend53) >= 1800000 && mStrSign != null) {
                addMessage53();
            }

            String[] messages = GoodsDataBase.getInstance().getMessage();
            if (messages == null || messages.length == 0) {
                if (isConnectionFail && mData52 != null && mStrSign != null && ((System.currentTimeMillis() - mTimeLast52) >= 60000)) {
                    doSend52();
                }
                continue;
            }
            logger.i("db count:" + messages.length);
            String message = messages[0];
            final String[] con = message.split(";");

            if (con[1] == null) {
                logger.e("message error = " + con[1]);
                GoodsDataBase.getInstance().deleteMessage(con[0]);
                continue;
            }

            if (con.length <= 2) {
                logger.e("message error1 = " + con[1]);
                GoodsDataBase.getInstance().deleteMessage(con[0]);
                continue;
            }
            message = con[1];
            String type = con[2];

            if (messages.length > 300) {
                // 删除除了流水以外的所有指令
                logger.i("start delete messages except 12");
                GoodsDataBase.getInstance().deleteMessageExceptType("12");
                logger.i("end delete messages");
                if (!type.equals("12"))
                    continue;
            }

//            if (!NetUtils.isNetAvailable()) {
//                logger.i("can not send message : net unvailable");
//                deleteUnusedMessage(type, con[0]);
//                continue;
//            }

            if (type.equals("72")) //72指令需要将最后的14位时间改成当前时间
            {
                message = message.substring(0, message.length() - 14) + Tools.getCurrentTime();
            }
            logger.i("send message : " + message);
            try {
                String respMessage = getServiceInfo(message);
                logger.i("receive message :" + respMessage);
                if (respMessage == null || respMessage.length() < 39) {
                    setConnectionState(true);
                    logger.e("Send " + type + " faild!");
                    deleteUnusedMessage(type, con[0]);
                } else {
                    setConnectionState(false);
                    //type = respMessage.substring(35, 37); // 控制码
                    String resultCode = respMessage.substring(37, 39);
                    if (resultCode.equals("00") || resultCode.equals("04") || resultCode.equals("05") || resultCode.equals("06") || resultCode.equals("09") || resultCode.equals("11") || resultCode.equals("12") || resultCode.equals("21") || resultCode.equals("31")||resultCode.equals("32")||resultCode.equals("34")||resultCode.equals("35")) {
                        logger.i("Send " + type + " success!");
                        GoodsDataBase.getInstance().deleteMessage(con[0]);
                        handleResponse(type, respMessage); //处理回复
                        mRetryCount = 0;
                    } else {
                        if (!type.equals("55")) {
                            logger.e("Send " + type + " faild!");
                        }
//                        mRetryCount++;
//                        if(mRetryCount > RETRY_COUNT)
//                        {
//                            mRetryCount = 0;
//                            logger.e("retry 3 times");
//                            GoodsDataBase.getInstance().deleteMessage(con[0]);
//                        }
//                        else {
                        deleteUnusedMessage(type, con[0]);
//                        }
                    }
                }
            } catch (NumberFormatException e) {
                logger.e("NumberFormatException: " + e.getMessage());
                deleteUnusedMessage(type, con[0]);
            } catch (SocketTimeoutException e) {
                setConnectionState(true);
                logger.e("SocketTimeoutException: " + e.getMessage());
                deleteUnusedMessage(type, con[0]);
            } catch (UnknownHostException e) {
                setConnectionState(true);
                logger.e("SocketTimeoutException: " + e.getMessage());
                deleteUnusedMessage(type, con[0]);
            } catch (SocketException e) {
                setConnectionState(true);
                logger.e("SocketTimeoutException: " + e.getMessage());
                deleteUnusedMessage(type, con[0]);
            } catch (IOException e) {
                setConnectionState(true);
                logger.e("IOException: " + e.getMessage());
                deleteUnusedMessage(type, con[0]);
            }
            SystemClock.sleep(5000);
        }
        run = false;
    }

    private void doSend52() {
        try {
            logger.i("send temp message :" + mData52);
            String respMessage = getServiceInfo(mData52);
            logger.i("receive temp message :" + respMessage);
            if (respMessage == null || respMessage.length() < 39) {
                setConnectionState(true);
            } else {
                setConnectionState(false);
                mTimeLast52 = System.currentTimeMillis();
            }
        } catch (IOException e) {
            setConnectionState(true);
            logger.e("IOException: " + e.getMessage());
        }
    }

    private void deleteUnusedMessage(final String type, final String id) {
        if (type.equals("52") || type.equals("53") || type.equals("54") || type.equals("55")) {
            GoodsDataBase.getInstance().deleteMessage(id);
        }
    }

    private String getServiceInfo(String message) throws NumberFormatException, UnknownHostException, SocketException, SocketTimeoutException, IOException {
        Socket socket = null;
        InputStream in = null;
        OutputStream out = null;
        byte[] buf;
        String respMessage = null;
        try {
            socket = new Socket();
            socket.setSoTimeout(20000);
            SocketAddress socAddress = new InetSocketAddress(Configure.getConfigData(Configure.CONFIG_SERVER_IP), Integer.parseInt(Configure.getConfigData(Configure.CONFIG_SERVER_PORT)));
            socket.connect(socAddress, 10000);
            in = socket.getInputStream();
            out = socket.getOutputStream();
            out.write(message.getBytes());
            out.flush();
            buf = new byte[4];
            in.read(buf);
            String sString = new String(buf);
            if ("".equals(sString.trim())) return message.substring(0, 37) + "88";
            buf = new byte[Integer.valueOf(sString.trim())];
            in.read(buf);
            respMessage = sString + new String(buf);
        } finally {
            if (socket != null) socket.close();
            if (in != null) in.close();
            if (out != null) out.close();
        }
        return respMessage;
    }

    private void handleResponse(final String pType, final String pMessage) {
        if (pType.equals("51")) //51签到
        {
            handle51(pMessage);
        } else if (pType.equals("53")) //53位置信息
        {
            handle53(pMessage);
        } else if (pType.equals("52")) //52轮询
        {
            handle52(pMessage);
        }
    }

    private void handle51(final String pMessage) {
        String serverTime = pMessage.substring(39, 53);
        logger.i("Sign success, serverTime = " + serverTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
        try {
            long serverTimeLong = sdf.parse(serverTime).getTime();
            if (Math.abs((new Date()).getTime() - serverTimeLong) > 10000) {
                SystemTools.setSystemTime(serverTime.substring(0, 8) + "." + serverTime.substring(8));
            }
            DriverThread.getInstance().setAvmTime(serverTime);
            //发送53指令，位置信息查询
            addMessage53();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void handle53(final String pMessage) {
        if (pMessage.length() <= 39) //不带经纬度信息,直接忽略
        {
            logger.i("53 no GPS message!");
            return;
        }
        //纬度 9
        String strLatitude = pMessage.substring(39, 48);
        double dLatitude = Double.parseDouble(strLatitude.substring(0, 3) + "." + strLatitude.substring(3)); //转换成double型
        //经度  9
        String strLongitude = pMessage.substring(48, 57);
        double dLongitude = Double.parseDouble(strLongitude.substring(0, 3) + "." + strLongitude.substring(3)); //转换成double型
        //报警偏差范围 5
        String strRange = pMessage.substring(57, 62);
        int iRange = Integer.parseInt(strRange);
        //流水号 3
        String strNo = pMessage.substring(62, 65);
        //发送54指令，定位信息
        StringBuffer str = new StringBuffer();
        String time = Tools.getCurrentTime();
        str.append(getMsgHeader());
        str.append("54");
        str.append(Tools.addLeftZero(String.valueOf(miLocationType), 3)); //故障代码
        if (mdLongitude < 0.0001 && mdLatitude < 0.0001) {
            //没有获取到位置坐标
            str.append("000000000");
            str.append("000000000");
            //偏差距离 5
            str.append("00000");
            //报警状态 1
            str.append("0");
        } else {
            //纬度 9
            strLatitude = String.valueOf(mdLatitude);
            logger.i("strLatitude:" + strLatitude);
            int pos = strLatitude.indexOf(".");
            if (pos >= 0) {
                strLatitude = Tools.addLeftZero(strLatitude.substring(0, pos), 3) + strLatitude.substring(pos + 1);
            }
            for (int i1 = 0; i1 < 9 - strLatitude.length(); i1++) {
                strLatitude += "0";
            }
            str.append(strLatitude);
            //经度  9
            strLongitude = String.valueOf(mdLongitude);
            logger.i("strLongitude:" + strLongitude);
            pos = strLongitude.indexOf(".");
            if (pos >= 0) {
                strLongitude = Tools.addLeftZero(strLongitude.substring(0, pos), 3) + strLongitude.substring(pos + 1);
            }
            for (int i2 = 0; i2 < 9 - strLongitude.length(); i2++) {
                strLongitude += "0";
            }
            str.append(strLongitude);
            //偏差距离 5
            int distance = (int) Tools.GetDistance(dLongitude, dLatitude, mdLongitude, mdLatitude);
//								int minus = Math.abs(iRange - distance);
            String strMinus = String.valueOf(distance);
            if (strMinus.length() > 5) {
                strMinus = strMinus.substring(0, 5);
            }
            str.append(Tools.addLeftZero(strMinus, 5));
            //报警状态 1
            str.append(iRange >= distance ? "0" : "1");
        }
        //流水号
        str.append(strNo);
        //定位时间
        str.append(time);
        String sendMessage = str.toString();
        sendMessage = Tools.addLeftZero(String.valueOf(sendMessage.length()), 4) + sendMessage;
        logger.i("insert db: " + sendMessage);

        insertDataToDB("54", sendMessage, "normal");
    }

    private void handle52(final String pMessage) {
        mTimeLast52 = System.currentTimeMillis();
        logger.i("pMessage:"+pMessage);
        String resultCode = pMessage.substring(37, 39);
        logger.i("resultCode:"+resultCode);
        if (resultCode.equals("00")) {
            mCurrentTime76 = DRIVER_TIME_76_NORMAL;
            return;
        } else if (resultCode.equals("04")) {
            logger.i("52 04:" + pMessage);
            //设置料道商品信息
            mCurrentTime76 = DRIVER_TIME_76_FAST;
            int count = (pMessage.charAt(56) - '0') & 0xFF;
            logger.i("52 04 count:" + count);
            if (count < 1 || pMessage.length() < count * 10 + 57 + 2 /*柜号*/ + 2 /*保留位*/) {
                logger.e("52 04 error");
                return;
            }
            int pos = 0;
            byte box = 0x00;
            StringBuffer boxStrBuffer = new StringBuffer();
            boxStrBuffer.append(pMessage.charAt(57)).append(pMessage.charAt(58));
            box = Byte.parseByte(boxStrBuffer.toString()); //柜号
            logger.i("52 04 box: " + Tools.bytesToHexString(box));
            pos = 59;
            for (int i1 = 0; i1 < count; i1++) {
                String dataByteArray = pMessage.substring(pos, pos + 10);
                StringBuffer dataStr = new StringBuffer();
                byte[] soldSendData = new byte[10];
                soldSendData[0] = 0x76; //0x76
                soldSendData[1] = 0x04; //设置料道信息0x04
                //柜号1字节
                soldSendData[2] = box; //柜号
                //货道号1字节
                dataStr.append(dataByteArray.charAt(0)).append(dataByteArray.charAt(1));
                soldSendData[3] = Byte.parseByte(dataStr.toString()); //货道号
                //商品ID1字节
                dataStr.delete(0, dataStr.length());
                dataStr.append(dataByteArray.charAt(2)).append(dataByteArray.charAt(3));
                soldSendData[4] = Integer.valueOf(dataStr.toString(), 16).byteValue(); //商品ID
                //价格2字节，角为单位
                dataStr.delete(0, dataStr.length());
                dataStr.append(dataByteArray.charAt(4)).append(dataByteArray.charAt(5)).append(dataByteArray.charAt(6)).append(dataByteArray.charAt(7));
                int price = Integer.parseInt(dataStr.toString());
                soldSendData[5] = (byte) ((price >> 8) & 0xFF);
                soldSendData[6] = (byte) (price & 0xFF); //价格
                //是否参加抽奖，1字节
                if (dataByteArray.charAt(8) == '1') {
                    soldSendData[7] = 0x01;
                } else {
                    soldSendData[7] = 0x00;
                }
                //预留，1字节
                soldSendData[8] = 0x00;
                //校验和
                byte sumByte = 0x00;
                for (int i2 = 0; i2 < soldSendData.length - 1; i2++) {
                    sumByte += soldSendData[i2];
                }
                soldSendData[9] = sumByte;
                DriverThread.getInstance().appendQueueData(soldSendData); //发送主动指令
                logger.i("76 04: " + Tools.bytesToHexString(soldSendData));
                pos += 10;
            }
            //发送55指令到服务器
            send55(pMessage);
        } else if (resultCode.equals("05")) {
            logger.i("52 05:" + pMessage);
            //设置料道加货信息
            mCurrentTime76 = DRIVER_TIME_76_FAST;
            int count = (pMessage.charAt(56) - '0') & 0xFF;
            logger.i("52 05 count:" + count);
            if (count < 1 || pMessage.length() < count * 4 + 57 + 2 /*柜号*/ + 2 /*保留位*/) {
                logger.e("52 05 error");
                return;
            }
            int pos = 0;
            byte box = 0x00;
            StringBuffer boxStrBuffer = new StringBuffer();
            boxStrBuffer.append(pMessage.charAt(57)).append(pMessage.charAt(58));
            box = Byte.parseByte(boxStrBuffer.toString()); //柜号
            logger.i("52 05 box: " + Tools.bytesToHexString(box));
            pos = 59;
            for (int i1 = 0; i1 < count; i1++) {
                String dataByteArray = pMessage.substring(pos, pos + 4);
                StringBuffer dataStr = new StringBuffer();
                byte[] soldSendData = new byte[8];
                soldSendData[0] = 0x76; //0x76
                soldSendData[1] = 0x05; //设置料道加货信息0x05
                //柜号1字节
                soldSendData[2] = box; //柜号
                //货道号1字节
                dataStr.append(dataByteArray.charAt(0)).append(dataByteArray.charAt(1));
                soldSendData[3] = Byte.parseByte(dataStr.toString()); //货道号
                //加货数量1字节
                dataStr.delete(0, dataStr.length());
                dataStr.append(dataByteArray.charAt(2)).append(dataByteArray.charAt(3));
                soldSendData[4] = Integer.valueOf(dataStr.toString(), 16).byteValue(); //加货数量
                //预留，2字节
                soldSendData[5] = 0x00;
                soldSendData[6] = 0x00;
                //校验和
                byte sumByte = 0x00;
                for (int i2 = 0; i2 < soldSendData.length - 1; i2++) {
                    sumByte += soldSendData[i2];
                }
                soldSendData[7] = sumByte;
                DriverThread.getInstance().appendQueueData(soldSendData); //发送主动指令
                logger.i("76 05: " + Tools.bytesToHexString(soldSendData));
                pos += 4;
            }
            //发送55指令到服务器
            send55(pMessage);
        } else if (resultCode.equals("06")) {
            logger.i("52 06:" + pMessage);
            //设置系统状态信息
            mCurrentTime76 = DRIVER_TIME_76_FAST;
            if (pMessage.length() < 57) {
                logger.e("52 06 error");
                return;
            }
            String dataByteArray = pMessage.substring(56);
            StringBuffer dataStr = new StringBuffer();
            byte[] soldSendData = new byte[18];
            soldSendData[0] = 0x76; //0x76
            soldSendData[1] = 0x06; //设置系统状态信息0x06
            //柜号1字节
            dataStr.append(dataByteArray.charAt(0)).append(dataByteArray.charAt(1));
            soldSendData[2] = Byte.parseByte(dataStr.toString()); //柜号
            //预留1字节
            soldSendData[3] = 0x00;
            //照明状态1字节
            dataStr.delete(0, dataStr.length());
            dataStr.append(dataByteArray.charAt(10)).append(dataByteArray.charAt(11));
            soldSendData[4] = Byte.parseByte(dataStr.toString()); //照明状态
            //日光灯时间4字节BCD码
            byte[] bcd = Tools.bcdStringToBytes(dataByteArray.substring(12, 16));
            soldSendData[5] = bcd[0];
            soldSendData[6] = bcd[1]; //开灯时间
            bcd = Tools.bcdStringToBytes(dataByteArray.substring(16, 20));
            soldSendData[7] = bcd[0];
            soldSendData[8] = bcd[1]; //停止时间
            //左室状态1字节
            dataStr.delete(0, dataStr.length());
            dataStr.append(dataByteArray.charAt(20)).append(dataByteArray.charAt(21));
            soldSendData[9] = Byte.parseByte(dataStr.toString()); //左室状态
            //右室状态1字节
            dataStr.delete(0, dataStr.length());
            dataStr.append(dataByteArray.charAt(22)).append(dataByteArray.charAt(23));
            soldSendData[10] = Byte.parseByte(dataStr.toString()); //右室状态
            //节能时间4字节BCD码
            bcd = Tools.bcdStringToBytes(dataByteArray.substring(24, 28));
            soldSendData[11] = bcd[0];
            soldSendData[12] = bcd[1]; //节能开始时间
            bcd = Tools.bcdStringToBytes(dataByteArray.substring(28, 32));
            soldSendData[13] = bcd[0];
            soldSendData[14] = bcd[1]; //节能停止时间
            //制冷温度1字节
            char c1 = dataByteArray.charAt(32); //正负号
            dataStr.delete(0, dataStr.length());
            dataStr.append(dataByteArray.charAt(33)).append(dataByteArray.charAt(34));
            int temp = Integer.parseInt(dataStr.toString()) & 0xFF;
            if (c1 == '-') {
                temp = temp | 0x80; //最高位置1
            }
            soldSendData[15] = (byte) temp;
            //加热温度1字节
            c1 = dataByteArray.charAt(35); //正负号
            dataStr.delete(0, dataStr.length());
            dataStr.append(dataByteArray.charAt(36)).append(dataByteArray.charAt(37));
            temp = Integer.parseInt(dataStr.toString()) & 0xFF;
            if (c1 == '-') {
                temp = temp | 0x80; //最高位置1
            }
            soldSendData[16] = (byte) temp;
            //校验和
            byte sumByte = 0x00;
            for (int i2 = 0; i2 < soldSendData.length - 1; i2++) {
                sumByte += soldSendData[i2];
            }
            soldSendData[17] = sumByte;
            DriverThread.getInstance().appendQueueData(soldSendData); //发送主动指令
            logger.i("76 06: " + Tools.bytesToHexString(soldSendData));
            //发送55指令到服务器
            send55(pMessage);
        } else if (resultCode.equals("09")) {
            logger.i("52 09:" + pMessage);
            //设置系统状态信息
            mCurrentTime76 = DRIVER_TIME_76_FAST;
            int count = (pMessage.charAt(56) - '0') & 0xFF;
            logger.i("52 09 count:" + count);
            if (count < 1 || pMessage.length() < count * 10 + 57 + 2 /*柜号*/ + 2 /*保留位*/) {
                logger.e("52 09 error");
                return;
            }
            int index;
            byte box;
            StringBuffer boxStrBuffer = new StringBuffer();
            boxStrBuffer.append(pMessage.charAt(57)).append(pMessage.charAt(58));
            box = Byte.parseByte(boxStrBuffer.toString()); //柜号
            logger.i("52 09 box: " + Tools.bytesToHexString(box));
            //pos = 59;
            index = 59;
            Map<Integer, ArrayList<WarrantyModel>> addCountMap = new HashMap<>();
            for (int j = 0; j < count; j++) {
                String dataByteArray = pMessage.substring(index, index + 10);
                index += 10;
                try {
                    int column = Integer.parseInt(dataByteArray.substring(0, 2));
                    String date = dataByteArray.substring(2, 8);
                    int stock = Integer.parseInt(dataByteArray.substring(8));
                    if (addCountMap.containsKey(column)) {
                        ArrayList<WarrantyModel> modelList = addCountMap.get(column);
                        modelList.add(new WarrantyModel(date, stock));
                    } else {
                        ArrayList<WarrantyModel> modelList = new ArrayList<>();
                        modelList.add(new WarrantyModel(date, stock));
                        addCountMap.put(column, modelList);
                    }
                } catch (NumberFormatException e) {
                    continue;
                }
            }

            for (int key : addCountMap.keySet()) {
                ArrayList<WarrantyModel> modelList = addCountMap.get(key);
                DriverThread.getInstance().setWarranty((int) box, key, WarrantyModel.list2string(modelList)); //更新到内存中
                //计算总加货数量
                int stock = 0;
                for (WarrantyModel model : modelList) {
                    stock += model.getStock();
                }
                //发送主控指令设置库存数量
                byte[] soldSendData = new byte[8];
                soldSendData[0] = 0x76; //0x76
                soldSendData[1] = 0x05; //设置料道加货信息0x05
                //柜号1字节
                soldSendData[2] = box; //柜号
                //货道号1字节
                soldSendData[3] = (byte) key; //货道号
                //加货数量1字节
                soldSendData[4] = (byte) stock; //加货数量
                //预留，2字节
                soldSendData[5] = 0x00;
                soldSendData[6] = 0x00;
                //校验和
                byte sumByte = 0x00;
                for (int i2 = 0; i2 < soldSendData.length - 1; i2++) {
                    sumByte += soldSendData[i2];
                }
                soldSendData[7] = sumByte;
                DriverThread.getInstance().appendQueueData(soldSendData); //发送主动指令
            }
            //保存到文件中
            DriverThread.getInstance().saveWarrantyData();
            //发送到后台监控
            addMessage84(box, DriverThread.getInstance().getWarrantyFromBox(box));
            //发送55指令到服务器
            send55(pMessage);
        } else if (resultCode.equals("11")) {
            logger.i("52 11:" + pMessage);
            //设置料道商品信息
            mCurrentTime76 = DRIVER_TIME_76_FAST;
            int count;
            try {
                count = Integer.parseInt(pMessage.substring(56, 58));
            } catch (NumberFormatException e) {
                logger.e("52 11 error:" + e.toString());
                return;
            }
            logger.i("52 11 count:" + count);
            if (count < 1 || pMessage.length() < count * 30 + 58 + 2/*柜号*/) {
                logger.e("52 11 error");
                return;
            }
            int pos = 0;
            byte box = 0x00;
            StringBuffer boxStrBuffer = new StringBuffer();
            boxStrBuffer.append(pMessage.charAt(58)).append(pMessage.charAt(59));
            box = Byte.parseByte(boxStrBuffer.toString()); //柜号
            logger.i("52 11 box: " + Tools.bytesToHexString(box));
            pos = 60;
            ArrayList<GoodsModel> goodsList = GoodsConfiguration.getGoodsList();
            ArrayList<GoodsModel> goodsDataBaseList = GoodsConfiguration.getGoodsDataBaseList();
            //13指令数组
            ArrayList<GoodsModel> goodsArray = new ArrayList<>();
            for (int i1 = 0; i1 < count; i1++) {
                String dataByteArray = pMessage.substring(pos, pos + 30);
                StringBuffer dataStr = new StringBuffer();
                byte[] soldSendData = new byte[10];
                soldSendData[0] = 0x76; //0x76
                soldSendData[1] = 0x04; //设置料道信息0x04
                //柜号1字节
                soldSendData[2] = box; //柜号
                //货道号1字节
                dataStr.append(dataByteArray.charAt(0)).append(dataByteArray.charAt(1));
                soldSendData[3] = Byte.parseByte(dataStr.toString()); //货道号
                //商品ID1字节
                dataStr.delete(0, dataStr.length());
                dataStr.append(dataByteArray.charAt(2)).append(dataByteArray.charAt(3));
                int code = Integer.valueOf(dataStr.toString(), 16);
                soldSendData[4] = (byte) code; //商品ID
                //价格2字节，角为单位
                dataStr.delete(0, dataStr.length());
                dataStr.append(dataByteArray.substring(20, 26));
                int price = 0;
                try {
                    price = Integer.parseInt(dataStr.toString());
                    price /= 10;
                } catch (NumberFormatException e) {
                    logger.e("52 11:" + e.toString());
                }
                soldSendData[5] = (byte) ((price >> 8) & 0xFF);
                soldSendData[6] = (byte) (price & 0xFF); //价格
                //是否参加抽奖，1字节
                soldSendData[7] = 0x00;
                //预留，1字节
                soldSendData[8] = 0x00;
                //校验和
                byte sumByte = 0x00;
                for (int i2 = 0; i2 < soldSendData.length - 1; i2++) {
                    sumByte += soldSendData[i2];
                }
                soldSendData[9] = sumByte;
                pos += 30;

                String barcode = dataByteArray.substring(4, 20).trim();
                GoodsModel goodsModel = null; //从商品库中找到这个商品
                Iterator<GoodsModel> iterator = goodsDataBaseList.iterator();
                while (iterator.hasNext()) {
                    GoodsModel model = iterator.next();
                    if (model.getBarCode().equals(barcode)) {
                        goodsModel = model;
                        break;
                    }
                }
//                for (GoodsModel model : Configure.goodsDataBaseList) {
//                    if (model.getBarCode().equals(barcode)) {
//                        goodsModel = model;
//                        break;
//                    }
//                }
                if(goodsModel == null)
                {
                    //商品库中没有找到这个商品
                    logger.e("can't find goods " + barcode + " from database");
                    continue;
                }

                DriverThread.getInstance().appendQueueData(soldSendData); //发送主动指令
                logger.i("76 04: " + Tools.bytesToHexString(soldSendData));

                boolean isFind = false;
                if (goodsList != null) {
                    for (int j = 0; j < goodsList.size(); j++) {
                        GoodsModel model = goodsList.get(j);
                        if (model.getBox() == box && model.getColumn() == soldSendData[3]) {
                            model.setBarCode(barcode);
                            if(goodsModel != null) {
                                model.setName(goodsModel.getName());
                            }
                            isFind = true;
                            break;
                        }
                    }
                }
                if (!isFind) {
                    String name = "";
                    if(goodsModel != null) {
                        name = goodsModel.getName();
                    }
                    GoodsModel goods = new GoodsModel();
                    goods.setBox(box);
                    goods.setColumn(soldSendData[3]);
                    goods.setName(name);
                    goods.setBarCode(barcode);
                    goods.setType("1");
                    goods.setImage("0.png");
                    goodsList.add(goods);
                }
                GoodsModel goods = new GoodsModel();
                goods.setBox(box);
                goods.setColumn(soldSendData[3]);
                goods.setBarCode(barcode);
                goods.setPrice(price * 10);
                Iterator<GoodsModel> goodsListModel = goodsList.iterator();
                while (goodsListModel.hasNext()) {
                    GoodsModel model = goodsListModel.next();
                    if (goods.equals(model)) {
                        goods.setDiscount(model.getDiscount());
                        break;
                    }
                }
//                for (GoodsModel model : Configure.goodsList) {
//                    if (model.equals(goods)) {
//                        goods.setDiscount(model.getDiscount());
//                        break;
//                    }
//                }
                goodsArray.add(goods);
                DownloadGoodsDatabaseThread.getInstance().startDownloadGoods(barcode, 1);
            }
            //update goods xml
            GoodsConfiguration.updateGoodsXML(goodsList);
            //发送55指令到服务器
            send55(pMessage);
            //发送13指令
            addMessage13(goodsArray);
        } else if (resultCode.equals("12")) {
            logger.i("52 12:" + pMessage);
            //设置商品打折率
            mCurrentTime76 = DRIVER_TIME_76_FAST;
            int count;
            try {
                count = Integer.parseInt(pMessage.substring(56, 58));
            } catch (NumberFormatException e) {
                logger.e("52 12 error:" + e.toString());
                return;
            }
            logger.i("52 12 count:" + count);
            if (count < 1 || pMessage.length() < count * 23 + 58) {
                logger.e("52 12 error");
                return;
            }
            int pos = 58;
            ArrayList<GoodsModel> goodsList = GoodsConfiguration.getGoodsList();
            ArrayList<GoodsModel> goodsDataBaseList = GoodsConfiguration.getGoodsDataBaseList();
            //13指令数组
            ArrayList<GoodsModel> goodsArray = new ArrayList<>();
            for (int i1 = 0; i1 < count; i1++) {
                String dataByteArray = pMessage.substring(pos, pos + 23);
                String barcode = dataByteArray.substring(0, 16).trim();
                int discount = 100;
                try {
                    discount = Integer.parseInt(dataByteArray.substring(16, 19));
                } catch (NumberFormatException e) {
                    logger.e("52 12 error:" + e.toString());
                }
                if (goodsList != null) {
                    for (int j = 0; j < goodsList.size(); j++) {
                        GoodsModel model = goodsList.get(j);
                        if (model.getBarCode().equals(barcode)) {
                            model.setDiscount(discount);
                        }
                    }
                }
                pos += 23;
                //13指令数据
                for (GoodsModel model : goodsList) {
                    if (model.getBarCode().equals(barcode)) {
                        String json = DriverThread.getInstance().getGoodsInfo(model.getBox(), model.getColumn());
                        if (json == null || "".equals(json)) {
                            continue;
                        }
                        GoodsModel jsonGoods = GoodsModel.fromJson(json);
                        GoodsModel goods = new GoodsModel();
                        goods.setBox(model.getBox());
                        goods.setColumn(model.getColumn());
                        goods.setBarCode(barcode);
                        goods.setPrice(jsonGoods.getPrice());
                        goods.setDiscount(discount);
                        goodsArray.add(goods);
                    }
                }
            }
            //update goods xml
            GoodsConfiguration.updateGoodsXML(goodsList);
            //发送55指令到服务器
            send55(pMessage);
            //发送13指令
            addMessage13(goodsArray);
        } else if (resultCode.equals("21")) {
            logger.i("52 21:" + pMessage);
            //POLL设置售卖软件配置
            if (pMessage.length() < 88) {
                logger.e("52 21 error");
                return;
            }
            char lock = pMessage.charAt(56);
            char retry = pMessage.charAt(57);
            if (lock == '1') {
                DriverThread.getInstance().mBoxLock = true;
            } else {
                DriverThread.getInstance().mBoxLock = false;
            }
            if (retry == '1') {
                DriverThread.getInstance().mBox11Retry = true;
            } else {
                DriverThread.getInstance().mBox11Retry = false;
            }
            DriverThread.getInstance().saveSettingFile();
        } else if (resultCode.equals("31")) {
            logger.i("52 31:" + pMessage);
            DownloadGoodsDatabaseThread.getInstance().startDownload(DownloadGoodsDatabaseThread.TYPE_PART);
        } else if (resultCode.equals("32")){
            logger.i("52 32:" + pMessage);
            DownloadGoodsDatabaseThread.getInstance().startDownload(DownloadGoodsDatabaseThread.TYPE_ALL);
        }else if(resultCode.equals("34")){
            logger.i("52 34:" + pMessage);
           StringBuilder saveBoxColumnStockBuilder=new StringBuilder();
            String numStr=pMessage.substring(56,58);//笔数
            logger.i("numStr:" + numStr);
            String boxStr=pMessage.substring(58,60);
            logger.i("boxStr:" + boxStr);//货柜
            String columnStrs=pMessage.substring(60);
            logger.i("columnStrs:" + columnStrs);
            String boxColumnStock = FileTools.getBoxColumnStock();
            logger.i("boxColumnStock:" + boxColumnStock);
            for (int i=0;i<Integer.parseInt(numStr);i++){
                String updateColumn=columnStrs.substring(0,4);
                String column=updateColumn.substring(0,2);//货道
                String stock=updateColumn.substring(2,4);//容量
                 logger.i("boxStr_column_stock:"+(boxStr+column+stock));
                 if(boxColumnStock==null){
                     logger.i("boxColumnStock文件为空,进行创建,并进行文件添加");
                     saveBoxColumnStockBuilder.append(boxStr+column+stock).append(",");
                 }else if(boxColumnStock!=null&&!boxColumnStock.contains(boxStr+column+stock)){
                     logger.i("不包含已存在的数据,进行文件追加");
                     saveBoxColumnStockBuilder.append(boxStr+column+stock).append(",");
                 }
                 //上传后台
                logger.i("updateColumn:" + updateColumn);
                columnStrs=columnStrs.substring(4);
            }
            logger.i("saveBoxColumnStockBuilder:" + saveBoxColumnStockBuilder.toString());
            FileTools.saveServiceMaxStockConfig(saveBoxColumnStockBuilder.toString());
        }else if(resultCode.equals("35")){
            logger.i("52 35:" + pMessage);
            if(Configure.context!=null){
                Intent intent=new Intent("com.easytouch.updateGoodsInfoService");
                Configure.context.sendBroadcast(intent);
            }
        }
    }

    //发送55指令
    private void send55(final String pMessage) {
        StringBuffer str = new StringBuffer();
        str.append(getMsgHeader());
        str.append("55"); //控制码
        str.append(pMessage.substring(37, 39)); //响应码
        str.append("00"); //回复确认
        str.append(pMessage.substring(39, 56)); //时间及流水号,原样返回
        String sendMessage = str.toString();
        sendMessage = Tools.addLeftZero(String.valueOf(sendMessage.length()), 4) + sendMessage;
        logger.i("insert db: " + sendMessage);

        insertDataToDB("55", sendMessage, "normal");
    }

    /**
     * 设置经纬度
     *
     * @param pLongitude 经度
     * @param pLatitude  纬度
     * @param pType      定位类型
     */
    public static void setLocationInfo(final double pLongitude, final double pLatitude, final int pType) {
        mdLongitude = pLongitude; //经度
        mdLatitude = pLatitude; //纬度
        miLocationType = pType; //定位类型
        isGPSEnable = true;
    }

//    public interface GPSHandler {
//        void init(final Context context);
//    }
//
//    public static void setGPSHandler(final GPSHandler handler)
//    {
//        if(handler != null)
//        {
//            mGPSHandler = handler;
//            isGPSEnable = true;
//        }
//    }
//
//    public static void removeGPSHandler()
//    {
//        mGPSHandler = null;
//        isGPSEnable = false;
//    }
}
